<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>系统环境及属性</title>
        <script src="./lib/axios.js"></script>
        <script src="./lib/vue.js"></script>
        <link rel="stylesheet" href="./lib/elementindex.css">
        <script src="./lib/elementindex.js"></script>

        <style>
            .el-dialog__header{
                    padding-top: 10px;
                    padding-bottom: 5px;
                }
            .el-dialog__body{
                padding-top: 0px;
            }
            .el-form-item {
                margin-bottom: 16px;/*2px. too small will overlap the error message*/
            }
            .el-form-item--small.el-form-item {
                margin-bottom: 14px;
            }
            .el-form-item__content {
                line-height: 35px;
                font-size: 14px;
            }
  /*          .el-checkbox__label {
               font-size: 10px;
            } */
            
            .hc-lang-editor {
                border: 1px solid #DCDFE6;
                border-radius: 4px;
            }
            
            .hc-lang-editor[readonly] {
                border: 1px solid #DCDFE6;
                border-radius: 4px;
                background-color: ghostwhite;
            }
            
            .hc-lang-editor:hover {
                border: 1px solid lightgray;
                border-radius: 4px;
            }
            </style>

    </head>
    <body>

        <div id='application-profiles' style="display: none;">
            <el-dialog width="70%" :visible.sync="showProfilesForm" title="配参环境设置">
                <el-row>
                    <el-col :span='24' style="font-size:small;margin-bottom: 1.125rem;">
                        <span style="color: darkgreen;">删除环境只影响管理可见性，不会删除数据，也不影响属性生效，可加回。</span>
                        <el-button size='mini' style="font-size:x-small;margin-bottom: 1.125rem;" type="success" @click="handleLoadFromNode">从节点中探测环境
                        </el-button>
                    </el-col>
                </el-row>
                <el-form ref="profilesForm" :model='mockmodel'>
                    <el-table v-loading="loading" ref="profileList" border :data="profileList" style="width: 100%;"
                        max-height="400px" row-key="id" :highlight-current-row="true">
                        <el-table-column label="环境代码" prop="code">
                            <template slot-scope="scope">
                                <el-form-item :rules="{validator:(x,y,z)=>handleProfileValueValidate(x,y,z,scope.row),trigger:'blur'}"
                                    :prop="'code'" style='width: 100%;'>
                                    <el-input v-if="editing === scope.row.id" style='width: 100%;' type="textarea" rows="1"
                                        v-model.trim="scope.row.code" placeholder="环境代码">
                                    </el-input>
                                    <span v-else>{{scope.row.code}}</span>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="环境名称" prop="name">
                            <template slot-scope="scope">
                                <el-form-item :rules="{validator:(x,y,z)=>handleProfileValueValidate(x,y,z,scope.row),trigger:'blur'}"
                                    :prop="'name'" style='width: 100%;'>
                                    <el-input v-if="editing === scope.row.id" type="textarea" rows="1" v-model.trim="scope.row.name"
                                        placeholder="环境名称">
                                    </el-input>
                                    <span v-else>{{scope.row.name}}</span>
                                </el-form-item>
                            </template>
                        </el-table-column>

                        <el-table-column label="生效节点" prop="name">
                            <template slot-scope="scope">
                                <span style="font-size:x-small;margin-bottom: 1.125rem;">{{scope.row.nodes}}</span>
                            </template>
                        </el-table-column>

                        <el-table-column title="操作" width="300px">
                            <template slot="header">
                                <el-button type="success" size='mini' @click="handleProfileAppend">
                                    创建
                                </el-button>
                            </template>
                            <template slot-scope="scope">
                                <el-button size='mini' @click="triggerProfileEdit(scope.row)">
                                    <span v-if="editing === scope.row.id">查看</span><span v-else>编辑</span>
                                </el-button>
                                <el-button size='mini' @click="handleProfileDelete(scope.row)">
                                    删除
                                </el-button>
                                <el-link size="mini" type="primary" icon="el-icon-bottom icon_class" @click="moveDown(scope.$index,scope.row)">下移</el-link>
                                &nbsp; <el-link size="mini" type="primary" icon="el-icon-top icon_class" @click="moveUp(scope.$index,scope.row)">上移</el-link>
                            </template>
                        </el-table-column>
                    </el-table>

                    <el-form-item>
                        <el-button @click='handleProfileUpdate' type="primary">确 认</el-button>
                        <el-button @click='showProfilesForm=false'>取 消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>
        <script type="module" id="application-profiles-script">
            function nodesGather(callback, vm, checkingTick=3)
            {
                let trycount = checkingTick;
                let applicationNodes = {list:[]};
                axios.get(window.hosturl +`/nodes-gather`).then(resp=>{
                    if(typeof resp.data!=='object' || resp.data.error)
                    {
                        vm.$message({showClose:true,type:"error",message:resp.data});
                        if(callback) callback(null);
                        return;
                    }
                    nodesGet();
                }).catch(ex=>{
                    vm.$message({showClose:true,type:"error",message:ex});
                    if(callback) callback(null);
                });
                
                function nodesGet()
                {
                    axios.get(window.hosturl +`/nodes-get`).then(resp=>{
                        if(typeof resp.data!=='object' || resp.data.error)
                        {
                            vm.$message({showClose:true,type:"error",message:resp.data});
                            if(callback) callback(null);
                            return;
                        }
                        let nodes = resp.data.data;
                        trycount =  applicationNodes.list.length === nodes.list.length ? trycount -1: checkingTick;
                        applicationNodes = nodes;
                        
                        if(trycount > 0)
                        {
                            setTimeout(nodesGet,100);
                        }else{
                            callback(applicationNodes);
                        };
                    }).catch(ex=>{
                        vm.$message({showClose:true,type:"error",message:ex});
                        if(callback) callback(null);
                    });
                }
            }
     
           
            window.vmApplicationProfiles = new Vue({
               el: '#application-profiles',
               data: {
                   showProfilesForm:false,
                   editing:null,
                   loading:false,
                   maxid:0,
                   profileItem:{},
                   profileList:[],
                   mockmodel:{},
               },
               mounted:function()
               {
                   this.$el.style.display= 'block';
               },
               methods: {
                   moveUp(index, row) {
                     var that = this
                     if (index > 0) {
                       const upDate = that.profileList[index - 1]
                       that.profileList.splice(index - 1, 1)
                       that.profileList.splice(index, 0, upDate)
                       this.$refs.profileList.setCurrentRow(row);
                     } else {
                       that.$message({showClose:true,type:"warning",message:'已经是第一条，不可上移'});
                     }
                   },
                   moveDown(index, row) {
                     var that = this
                     if ((index + 1) === that.profileList.length) {
                       that.$message({showClose:true,type:"warning",message:'已经是最后一条，不可下移'});
                     } else {
                       const downDate = that.profileList[index + 1]
                       that.profileList.splice(index + 1, 1)
                       that.profileList.splice(index, 0, downDate)
                       this.$refs.profileList.setCurrentRow(row);
                     }
                   },
                   showform:function(profileItem,callback)
                   {
                       this.profileItem = profileItem;
                       this.profileList = JSON.parse(profileItem.item_value).list;
                       let maxid = 0
                       this.profileList.forEach(it=>it.id = ++maxid);
                       this.maxid = maxid;
                       this.callback = callback;
                       this.showProfilesForm = true;
                   },
                   triggerProfileEdit:function(row)
                   {
                       let self = this;
                       if(!this.editing)
                       {
                           this.editing = row.id;
                       } else{
                           this.$refs['profilesForm'].validate((valid) => {
                                     if (valid) self.editing = 0 ; else return false;
                                   });
                       }
                   },
                   handleProfileUpdate:function()
                   {
                     this.profileItem.item_value = JSON.stringify({list:this.profileList});
                     if(this.callback)this.callback(this.profileItem)
                     this.showProfilesForm =false;
                   },
                   
                   handleProfileAppend:function()
                   {
                       let self = this;
                       this.$refs['profilesForm'].validate((valid) => {
                                 if (valid) doAction(); else return false;
                               });
                        
                        function doAction(){
                           let profile = {id: ++self.maxid,code:'',name:''};
                           self.profileList.splice(self.profileList.length,0,profile);
                           self.editing = profile.id;
                        }
                   },
                   handleProfileDelete:function(row)
                   {
                       let self = this;
                       this.$confirm(`删除配参环境[${row.code}], 是否继续?`, '提示', {
                           cancelButtonText: '取消',
                           confirmButtonText: '确定',
                           type: 'warning',
                           center: true
                       }).then(doDelete).catch(()=>{console.log(`${row} is cancelled`);});
                       
                        function doDelete()
                        {
                           let index = self.profileList.findIndex(it=>it.id===row.id);
                           self.profileList.splice(index,1); 
                        }
                   },
                   handleProfileValueValidate:function(rule,value,callback,row)
                   {
                       let val = row[rule.field];
                       if(!val){ 
                           callback(new Error('不能为空'));
                        };
                        
                        callback();
                   },
                   handleLoadFromNode:function()
                   {
                       window.vmApplicationProfiles.loading=true;
                       nodesGather(mergeNodeProfiles,window.vmApplicationProfiles, 3);
                   }
               },//end of method
           });
                
            
            function mergeNodeProfiles(nodes)
            {
                console.warn("nodes",nodes);
                window.vmApplicationProfiles.loading=false;
                if(!nodes) return;
                
                nodes.list.forEach(node=>{
                   node.profiles.forEach(prof=>{
                        merge(window.vmApplicationProfiles.profileList,prof,node.name)
                   }) ;
                });
                
                function merge(profileList,prof,node)
                {
                    console.warn("profileList,prof,node",profileList,prof,node);
                    let profile  = profileList.find(it=>it.code==prof);
                    if(profile)
                    {
                        if(!profile.nodes) profile.nodes = [node];
                        else {
                            let nf = profile.nodes.find(n=>n==node);
                            if(!nf)profile.nodes.push(node);
                        }
                    }
                    else {
                        profileList.push({code:prof,name:prof,nodes:[node]});
                    }
                }
            }          
            
        </script>



        <div id='app' style="display: none;">
            <el-card style="font-size:small;margin-bottom: 1.125rem;">
                <el-link @click="handleOpen">&lt;&lt;&lt;open</el-link>
            </el-card>

        </div>

        <script type="module" id="system-detail-script">
            window.hosturl = document && document.location.href.startsWith('http://127.0.0.1:8848') ? 'http://localhost/resources' : '.';
            
            window.vmSystem = new Vue({
             el: '#app',
             data: {
                
             },
             mounted:function()
             {
                 this.$el.style.display= 'block';
                 window.vmApplicationProfiles.showform(
                 {item_value:'{"list":[{"code":"default","name":"默认"}]}'},
                 profiles =>{
                     console.warn("profiles returned",profiles);
                 }
                 );
             },
             methods: {
                 handleOpen()
                 {
                    window.vmGrayPublish.showform();
                 }
             },//end of method
         });
         
        
      </script>
        <script type="module" id="ttt-script">
        </script>

        <div id='bottom'></div>
    </body>
</html>
